<template>
  <div>
    <el-form label-width="80px" :inline="false" size="default">
      <el-form-item label="SPU 名称">
        <span>{{ spuInfo.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU 名称">
        <el-input v-model="skuInfo.skuName" size="default" clearable></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input v-model="skuInfo.price" size="default" clearable></el-input>
      </el-form-item>
      <el-form-item label="重量(千克)">
        <el-input v-model="skuInfo.weight" size="default" clearable></el-input>
      </el-form-item>
      <el-form-item label="规格描述">
        <el-input v-model="skuInfo.skuDesc" size="default" clearable type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form label-width="80px" :inline="true" size="default">
          <el-form-item
              :label="attrInfo.attrName"
              v-for="attrInfo in attrInfoList"
              :key="attrInfo.id"
          >
            <el-select placeholder="请选择" clearable v-model="attrInfo.selectData">
              <el-option
                  :value="`${attrInfo.id}:${attrValue.id}`"
                  v-for="attrValue in attrInfo.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="80px" :inline="true" size="default">
          <el-form-item
              v-for="selfAttr in saleAttrSelfList"
              :key="selfAttr.id"
              :label="selfAttr.saleAttrName"
          >
            <el-select placeholder="请选择" clearable v-model="selfAttr.selectData">
              <el-option
                  :value="`${selfAttr.id}:${selfAttrValue.id}`"
                  v-for="selfAttrValue in selfAttr.spuSaleAttrValueList"
                  :key="selfAttrValue.id"
                  :label="selfAttrValue.saleAttrValueName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片列表">
        <el-table :data="spuImageList" border stripe @selection-change="addImageList">
          <el-table-column type="selection" width="50"/>
          <el-table-column label="图片">
            <template #default="{row}">
              <el-image style="width: 100px" :src="row.imgUrl"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button @click="toImgDefault(row)" v-if="row.isDefault==='0'" type="primary" size="small">设为默认
              </el-button>
              <el-tag v-else>默认图片</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">保存</el-button>
        <el-button @click="emit('changeType', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {defineComponent} from "vue";

export default defineComponent({
  name: "SkuForm",
});</script>

<script setup lang="ts">
//接收切换type的自定义事件
import type {SpuItemType, spuSaleAttrListType, spuSaleImgItemType, spuSaleImgListType} from "@/api/spu";
import {onMounted, ref} from "vue";
import {type AttrInfoListType, reqGetAttrInfoList} from "@/api/attr";
import {reqSaleAttrSelf, reqSpuImageList, type SpuInfoType} from "@/api/spu";
import useCategoryStore from "@/stores/category";
import {storeToRefs} from "pinia";
import {ElMessage} from "element-plus/es";
import type {SkuItemDetailType} from "@/api/sku";
import {reqAddSku} from "@/api/sku";

// 获取自定义时间 用于返回spuList
const emit = defineEmits<{
  (event: "changeType", type: number, row?: SpuItemType): void;
}>();

/*进入skuList组件时  发送获取对应三级分类的条件下平台属性请求 发送获取对应spuId下销售属性请求 发送获取对应spuId下的图片列表请求*/
// 保存平台属性
const attrInfoList = ref<AttrInfoListType>([]);
// 保存spu自己的销售属性
const saleAttrSelfList = ref<spuSaleAttrListType>([])
// 保存图片列表
const spuImageList = ref<spuSaleImgListType>([])

// 获取三级分类的条件  用于发送平台属性请求
const cateStore = useCategoryStore()
const {categoryList1Id, categoryList2Id, categoryList3Id} = storeToRefs(cateStore);

// 获取spuId  发送获取对应spuId下销售属性请求 发送获取对应spuId下的图片列表请求
const props = defineProps<{  // 得到需要添加sku属性值得 spu数据
  spuInfo: SpuInfoType
}>()

// 获取 平台属性 spu自己的销售属性 图片列表
const getList = async () => {
  try {
    const p1 = reqGetAttrInfoList(
        categoryList1Id.value as number,
        categoryList2Id.value as number,
        categoryList3Id.value as number
    )
    const p2 = reqSaleAttrSelf(props.spuInfo.id as number)
    const p3 = reqSpuImageList(props.spuInfo.id as number)

    // 三个请求一起发送
    const result = await Promise.all([p1, p2, p3]);

    // 保存平台属性
    attrInfoList.value = result[0]
    // 添加额外属性  收集 attrId 和 attrValueId  添加需要
    attrInfoList.value.forEach(item => item.selectData = '')

    // 保存spu自己的销售属性
    saleAttrSelfList.value = result[1]
    // 添加额外属性  收集 添加需要的 saleAttrId 和 saleAttrValueId
    saleAttrSelfList.value.forEach(item => item.selectData = '')

    // 保存图片列表
    spuImageList.value = result[2]
    // 添加额外属性  收集 用于收集默认图片
    spuImageList.value.forEach(item => item.isDefault = '0')

  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

// 挂载时获取
onMounted(() => {
  // 获取数据
  getList()
});

//  创建模板  收集skuForm表单数据
const skuInfo = ref<SkuItemDetailType>({
  spuId: props.spuInfo.id as number, //所在的spuId
  price: 0, //当前sku的价格
  skuName: '', //当前sku的名称
  skuDesc: '', //当前sku的描述
  weight: '', //当前sku的重量
  tmId: props.spuInfo.tmId, //当前sku所在的品牌id
  category3Id: categoryList3Id.value as number, //当前sku所在的三级分类的id
  skuDefaultImg: '', //当前sku的默认的图片
  isSale: 1, //当前sku是否上架
  createTime: '', //当前sku的创建时间
  skuImageList: [], //当前sku图片列表
  skuAttrValueList: [], //当前sku属性值列表(平台属性)
  skuSaleAttrValueList: [] //当前sku销售属性值列表
})

// 收集到的图片数据类型
type imgItem = {
  id: number;
  imgName: string;
  imgUrl: string;
  spuId: number;
  isDefault: string
}

// 用于保存收集到的图片列表的数据
const imageList = ref<imgItem[]>([])

// 收集图片列表数据的函数
const addImageList = (selection: imgItem[]) => {
  console.log(selection)
  imageList.value = selection
}

// 设置默认图片
const toImgDefault = (row: spuSaleImgItemType) => {
  // 使用排他
  spuImageList.value.forEach(item => item.isDefault = '0')

  row.isDefault = '1';

  // 将谁是默认图片的地址 收集到 skuInfo 后续提交需要
  skuInfo.value.skuDefaultImg = row.imgUrl
}

// 添加sku功能 提交的回调
const submit = async () => {
  // 整理图片的数据
  skuInfo.value.skuImageList = imageList.value.map(item => {
    return {
      imgName: item.imgName, //图片名称
      imgUrl: item.imgUrl, //图片地址
      spuImgId: item.id, // 在spu中的id
      isDefault: item.isDefault,//是否是当前的默认图片
    }
  })

  // 整理品牌属性的数据
  attrInfoList.value.forEach(item => {
    if (!item.selectData) return

    const [attrId, attrValueId] = item.selectData.split(':')
    skuInfo.value.skuAttrValueList.push({
      attrId: +attrId,
      valueId: +attrValueId
    })
  })

  // 整理销售属性的数据
  saleAttrSelfList.value.forEach(item => {
    if (!item.selectData) return

    const [saleAttrId, saleAttrValueId] = item.selectData.split(':')
    skuInfo.value.skuSaleAttrValueList.push({
      saleAttrId: +saleAttrId,
      saleAttrValueId: +saleAttrValueId
    })
  })

  // 发送请求
  try {
    await reqAddSku(skuInfo.value);
    ElMessage.success("添加sku成功");
    emit("changeType", 0);
  } catch (e: any) {
    ElMessage.error(e.message);
  }
}
</script>

<style scoped>

</style>